<?php

namespace App\Tasks;

use App\Clients\Yisheng\TermStlmTotal;
use App\Clients\Yisheng\TradeGetTotal;
use App\Models\MallDateFinance;
use GuzzleHttp\Exception\GuzzleException;

class YishengSyncDatasTask extends MeiTuanMallTask
{
    /**
     * @throws GuzzleException
     */
    public function execute(): void
    {
        $startDate = $this->maxDate();
        $diffDate = (strtotime(date("Y-m-d",time())) - strtotime(date("Y-m-d",strtotime($startDate)))) / 86400;
        $queryDates = [];
        foreach (range(0,$diffDate,1) as $index=>$item){
            $beginDate = date("Y-m-d H:i:s",strtotime($startDate) + 1 * $index * 86400);
            $endDate = date("Y-m-d H:i:s",strtotime($beginDate) + 86399);
            $queryDates[] = [
                "income"=>[
                    "termCodes"=>$this->mall->merchant_no,
                    "tradeTime"=>[
                        $beginDate,
                        $endDate
                    ],
                    "tradeState"=>0,
                    "splitSettleFlag"=>100,
                    "searchField"=>"RefNo",
                ],
                "sub"=>[
                    "stlmDate"=>[
                        $beginDate,
                        $endDate
                    ],
                    "termCodes"=>$this->mall->merchant_no,
                ]
            ];
        }

        $incomeClient = new TradeGetTotal($this->account);
        $subClient = new TermStlmTotal($this->account);
        foreach ($queryDates as $queryDate)
        {
            $udate = date("Y-m-d",strtotime($queryDate["income"]["tradeTime"][0]));
            var_dump($udate);
            $model = MallDateFinance::query()
                ->where("merchant_no",$this->mall->merchant_no)
                ->where("date",$udate)
                ->first();
            if(!empty($model) && $model->is_update == 1){
                continue;
            }
            $response = $incomeClient->loopExecute($queryDate["income"])->contents();
            $income = round($response["totalAmount"] / 100,2);
            $response = $subClient->loopExecute($queryDate["sub"])->contents();
            $subaoumt = 0;
            if(!empty($response)){
                $subaoumt = round($response["receiveTotalAmount"] / 100,2);
            }
            empty($model) and $model = new MallDateFinance;
            $model->bill_no = $udate;
            $model->merchant_no = $this->mall->merchant_no;
            $model->date = $udate;
            $model->income = $income;
            $model->settle_money = $subaoumt;
            $model->save();
        }
    }
}
